<template>
	<page-meta :root-font-size="fontSize+'px'"></page-meta>
	<view
		:style="{
			width: windowWidth,
			height: windowHeight,
		}"
	>
		<enterprise v-if="liveType == 0" :joined-group-id="joinedGroupId"  :liveId="liveId"/>
		<liveroom v-if="liveType == 1" :joined-group-id="joinedGroupId"  :liveId="liveId"/>
	</view>
</template>

<script>
	import { mapGetters } from 'vuex';
	import { 
		RoomStatus
	} from '@/utils/constants.js';
	import { convertToCamel, throttle } from '@/utils/common.js';
	import Enterprise from '../components/enterprise/enterprise.vue';
	import Liveroom from '../components/liveroom/liveroom.vue';
	import rootFontSize from '@/mixins/rootFontSize.js';
	export default {
		components: {
			Enterprise,
			Liveroom
		},
		data() {
			return {
				fetching: false,
				liveId: '',
				liveType:'',
				joinedGroupId: '', // 已加入的消息组id
				windowHeight: '100%',
				windowWidth: '100%',
				roomData:{},
				baseUrl: this.config.baseUrl,
				uid:0,
				is_share:0,
				share_user:0,
				authcode:uni.getStorageSync("authcode"),
				applet_id:uni.getStorageSync("applet_id"),
			};
		},
		mixins: [rootFontSize],
		computed: {
			...mapGetters({
				roomInfo: 'liveroom/info',
			}),
		},
		created() {
			const res = uni.getSystemInfoSync();
			this.windowHeight = res.windowHeight + 45 + 'px';
			this.windowWidth = res.windowWidth + 'px';
		},
		onShow() {
			
		},
		onLoad(query) {
			this.liveId = query.liveId
			this.liveType = query.liveType
			this.is_share = query.is_share || 0
			this.share_user = query.share_user || 0
			if (!query.liveId) {
				uni.redirectTo({
					url: '/pages/live/roomList/roomList',
				});
				return;
			}
			// if (this.authcode) {

				if(this.is_share && this.share_user){
					this.createShareLog()
				}
				this.fetchRoomDetail(query.liveId);
			// }
		},
		async onUnload() {
			this.$store.commit('liveroom/reset');
			uni.$emit('socketClose')
		},
		// #ifdef MP
		onShareAppMessage: function () {
			let that = this;
			let share_token = uni.getStorageSync("share_token");
			return {
				title: that.roomData.title || '',
				imageUrl: that.baseUrl + that.roomData.shareImg,
				path: '/pages/live/room/room?is_share=1&liveType=' + that.liveType + '&liveId=' + that.liveId + '&share_token=' + share_token+'&share_user='+that.uid+'&applet_id='+that.applet_id
			};
		},
		// #endif
		methods: {
			toLogin(){
				let authcode = uni.getStorageSync("authcode");
				if (!this.authcode) {
					let pages = getCurrentPages();
					let page = pages[pages.length - 1];
								// this.tips('2222')
					this.app.noLoginModals(page, '您暂未登陆，请登陆后再观看直播.',true);
				}
			},
			fetchRoomDetail(roomId) {
				let that = this
				if (this.fetching) {
					return;
				}
				uni.showLoading({
					title: '直播间数据加载中...',
				});
				this.fetching = true;
				this.$u.get('live/api.index/room',{roomId:roomId}).then(res => {
					const data = convertToCamel(res.data);
					// console.log(data)
					uni.setNavigationBarTitle({
						title:data.title
					})
					this.roomData = data
					if(this.authcode){
						this.getUid()
					}
					// console.log('detail-->', data);
					this.$store.commit('liveroom/updateInfo', data);
					// 缓存当前直播间id
					// uni.setStorage({
					// 	key: LatestLiveidStorageKey,
					// 	data: roomId,
					// });
				}).catch((e) => {
					if(e.data.action == 'pay'){
						let pages = getCurrentPages();
						let page = pages[pages.length - 1];
						let return_url = '/'+page.route+'?'+this.app.objectToQueryString(page.options)
						uni.showModal({
							title:'付费直播',
							showCancel:false,
							content:e.msg,
							success(e) {
								let authcode = uni.getStorageSync("authcode");
								if (!that.authcode) {
									that.toLogin()
								}else{
									that.$u.post('live/api.index/createOrder',{
										live_id:roomId,
										return_url:return_url
									}).then(res => {
										that.navTo('/pages/live/order/pay?order_id='+res.data.order_id)
									});
								}
							}
						})
					}else{
						uni.showModal({
							title:'提示',
							showCancel:false,
							content:e.msg,
							success(e) {
								that.navTo('/pages/shop/index/index')
							}
						})
					}
					
					return
				})
				.finally(() => {
					uni.hideLoading();
					this.fetching = false;
				});

			},
			getUid(){
				this.$u.post('member/api.center/getCenterInfo').then(res => {
					if(res.code == 1){
						this.uid = res.data.userInfo.user_id;
						this.getShare()
					}
				});
			},
			createShareLog(){
				this.$u.post('live/api.index/share',{share_user:this.share_user,live_id:this.liveId}).then(res => {

				});
			},
			getShare() {
				let _this = this;
				// js-sdk文档中规定，url的格式要求：
				// 确认url是页面完整的url(请在当前页面alert(location.href.split('#')[0])确认)，包括'http(s): '部分，以及'？'后面的GET参数部分,但不包括'#'hash后面的部分
				var url = location.href.split('#')[0];
				this.$u.post('/publics/api.index/getWxShare', {
					url: url,
				}).then(res => {
					uni.hideLoading();
					var shareConfig = res.data;
					_this.token = res.data.token
					_this.$wxjs.config({
						debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
						appId: res.data.wxShare.appId, // 公众号的唯一标识  
						timestamp: res.data.wxShare.timestamp, // 生成签名的时间戳  
						nonceStr: res.data.wxShare.nonceStr, // ，生成签名的随机串  
						signature: res.data.wxShare.signature, // 签名  
						// surl: res.data.surl, //自己添加的，debug为true的时候可以网页打印出对应的URL是否正确
						jsApiList: ['updateAppMessageShareData','updateTimelineShareData']})
						_this.$wxjs.ready(() => {
							let links = window.location.href;
							let shareLink = ''
							if(_this.token){
								if (links.indexOf('?') > 0){
									shareLink = links + '&is_share=1&share_token=' + res.data.token+'&share_user='+_this.uid+'&applet_id='+_this.applet_id; 
								}else{
									shareLink = links + '?is_share=1&share_token=' + res.data.token+'&share_user='+_this.uid+'&applet_id='+_this.applet_id; 
								}
							}else{
								shareLink = links;
							}
							_this.$wxjs.updateAppMessageShareData({
								title: _this.roomData.title, // 分享标题 
								desc: _this.roomData.desc, // 分享描述  
								link: shareLink, // 当前页面链接  
								imgUrl: _this.baseUrl + _this.roomData.shareImg, // 分享图标   
								success(res) {
								},
								cancel(res) {}
							})
							// 自定义“分享到朋友圈”及“分享到QQ空间”按钮的分享内容（1.4.0）
							_this.$wxjs.updateTimelineShareData({
								title: _this.roomData.title, // 分享标题 
								desc: _this.roomData.desc, // 分享描述  
								link: shareLink, // 当前页面链接  
								imgUrl: _this.baseUrl + _this.roomData.shareImg, // 分享图标  
								success(res) {},
								cancel(res) {}
							})
						})
					}).catch(err => {
						console.log(err);
				})
			}
		},
	}
</script>

<style lang="scss">
</style>
